package com.cxx.filter;

import com.alibaba.fastjson.JSONObject;
import com.cxx.pojo.Result;
import com.cxx.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class RequsetFilter implements Filter {
    private JwtUtils jwtUtils=new JwtUtils();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        // 此处 setHeader、addHeader 方法都可用。但 addHeader时写多个会报错：“...,but only one is allowed”
        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.addHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        // 解决预请求（发送2次请求），此问题也可在 nginx 中作相似设置解决。
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Cache-Control,Pragma,Content-Type,Token, Content-Type");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        String method = request.getMethod();
        if (method.equalsIgnoreCase("OPTIONS")) {
            servletResponse.getOutputStream().write("Success".getBytes("utf-8"));
        } else {
            String requestURI = request.getRequestURL().toString();
            //2.如果是登录页面直接放行
            if(requestURI.contains("login")||requestURI.contains("regist")){
                filterChain.doFilter(request,response);
                return;
            }
            //3.获取请求中的令牌
            String jwt=request.getHeader("token");
            //4.判断令牌是否存在，如不存在，返回错误信息(未登录）
            if(!StringUtils.hasLength(jwt)){
                Result error= Result.error("NOT_LOGIN");
                String notLogin= JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                return;
            }
            //5.解析token,如果解析失败，返回错误信息（未登录）
            try {
                jwtUtils.parseJwt(jwt);
            } catch (Exception e) {
                e.printStackTrace();
                Result error= Result.error("NOT_LOGIN");
                String notLogin= JSONObject.toJSONString(error);
                response.getWriter().write(notLogin);
                return;
            }
            //6.令牌合法，放行
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
